package com.front.exception;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.google.gson.Gson;


public class FrontExceptionHandler implements HandlerExceptionResolver {

	/***
	 *  判断是否是ajax请求
	 * @param httpRequest
	 * @return
	 */
    private boolean isAjax(HttpServletRequest httpRequest)
    {
        return "XMLHttpRequest".equalsIgnoreCase(httpRequest.getHeader("X-Requested-With"));
    }
    
    
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) 
	{
		response.setCharacterEncoding("UTF-8");
		if(ex instanceof LoginException)
		{
		    if (isAjax(request)) //是ajax请求  返回错误代码
            {
		      try
		      {
		      PrintWriter out = response.getWriter();
		   	  response.setStatus(403);
		   	  Map<String,Object>result=  new HashMap<String, Object>();
		   	  result.put("errorcode", 403);
		   	  result.put("message", "您尚未登录或登录时间过长,请重新登录!");
              out.println(new Gson().toJson(result));
              out.flush();
              out.close();
              }catch (Exception e) {
            	  e.printStackTrace();
			  }
            }
		    else
		    {
		    	ModelAndView view = new ModelAndView("redirect:/");
		    	return view;
		    }
		}else  
		{
			 if (isAjax(request)) //是ajax请求  返回错误代码
			 {
				   try
				   {
				      PrintWriter out = response.getWriter();
				   	  response.setStatus(500);
				   	  Map<String,Object>result=  new HashMap<String, Object>();
				   	  result.put("errorcode", 500);
				   	  result.put("message", "服务器网络异常，请刷新重试!");
		              out.println(new Gson().toJson(result));
		              out.flush();
		              out.close();
		              }catch (Exception e) {
		            	  e.printStackTrace();
					 }
			 }
			 else
			 {
			    	ModelAndView view = new ModelAndView("redirect:/");
			    	return view;
			 }
		}
		return null;
	}

}
